{{define "admin/websites.html"}}
{{template "default/header.html" .}}

<main role="main" class="content">
    <div class="card">
        <div class="card-header bg-white border-0 py-3 d-flex flex-wrap flex-md-nowrap align-items-center gap-2">
            <div><h4 class="mb-2 mb-md-0 fw-bold webstack-title">网站管理</h4></div>
            <div class="d-flex flex-wrap flex-md-nowrap align-items-center w-100 gap-2">
                <div class="dropdown mb-2 mb-md-0">
                    <button class="btn btn-outline-primary btn-sm dropdown-toggle" type="button" id="groupFilterDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        筛选分组
                    </button>
                    <div class="dropdown-menu dropdown-menu-end" aria-labelledby="groupFilterDropdown">
                        <a class="dropdown-item" href="/admin/websites">全部</a>
                        {{ range .groups }}
                        <a class="dropdown-item" href="/admin/websites?group_id={{ .Id }}">{{ .Name }}</a>
                        {{ end }}
                    </div>
                </div>
                <form class="webstack-search-form d-flex flex-wrap align-items-center mb-2 mb-md-0" method="get" action="/admin/websites">
                    <input type="hidden" name="group_id" value="{{ .current_group_id }}">
                    <input type="text" class="form-control form-control-sm rounded-pill me-2" name="name" placeholder="搜索名称" value="{{ .search_name }}">
                    <button type="submit" class="btn btn-outline-success btn-sm me-2 rounded-pill">搜索</button>
                    <a href="/admin/websites" class="btn btn-outline-secondary btn-sm rounded-pill">重置</a>
                </form>
                <div class="webstack-header-actions">
                    <button class="btn btn-primary btn-sm rounded-pill" data-toggle="modal" data-target="#websiteModal" onclick="resetForm()">新增网站</button>
                </div>
            </div>
        </div>

        <div class="card-body p-3">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>分组</th>
                        <th>URL</th>
                        <th>Logo</th>
                        <th>描述</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="websiteList">
                    {{ range .websites }}
                    <tr>
                        <td>{{ .Id }}</td>
                        <td class="name" title="{{ .Name }}">{{ .Name }}</td>
                        <td>{{ .Group.Name }}</td>
                        <td title="{{ .Url }}">{{ .Url }}</td>
                        <td><img src="{{ .Logo }}" style="width: 32px; border-radius: 8px;"/></td>
                        <td class="description" title="{{ .Description }}">{{ .Description }}</td>
                        <td>{{ .CreatedAt | formatDate }}</td>
                        <td>
                            <button class="btn btn-outline-warning btn-sm rounded-pill mb-1" data-toggle="modal" data-target="#websiteModal" onclick='editWebsite({{ .Id }}, "{{ .Name }}", "{{ .GroupId }}", "{{ .Url }}", "{{ .Logo }}", "{{ .Description }}")'>编辑</button>
                            <button class="btn btn-outline-danger btn-sm rounded-pill mb-1" onclick="deleteWebsite({{ .Id }})">删除</button>
                        </td>
                    </tr>
                    {{ end }}
                    </tbody>
                </table>
            </div>

            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    {{ if gt .page 1 }}
                    <li class="page-item">
                        <a class="page-link" href="/admin/websites?page={{ max 1 (sub .page 1) }}&group_id={{ .current_group_id }}">上一页</a>
                    </li>
                    {{ else }}
                    <li class="page-item disabled">
                        <a class="page-link" href="#" tabindex="-1" aria-disabled="true">上一页</a>
                    </li>
                    {{ end }}
            
                    {{ $curPage := .page }}
                    {{ $curGroup := .current_group_id }}
                    {{ $searchName := .search_name }}
                    {{ range $i := seq 1 .total_pages }}
                       <!-- 调试：$i={{ $i }} $curPage={{ $curPage }} eq={{ eq $i $curPage }} -->
                        <li class="page-item {{ if eq $i $curPage }}active{{ end }}">
                            <a class="page-link" href="/admin/websites?page={{ $i }}&group_id={{ $curGroup }}{{if $searchName}}&name={{$searchName}}{{end}}">{{ $i }}</a>
                        </li>
                    {{ end }}
            
                    {{ if lt .page .total_pages }}
                    <li class="page-item">
                        <a class="page-link" href="/admin/websites?page={{ min .total_pages (add .page 1) }}&group_id={{ .current_group_id }}">下一页</a>
                    </li>
                    {{ else }}
                    <li class="page-item disabled">
                        <a class="page-link" href="#" tabindex="-1" aria-disabled="true">下一页</a>
                    </li>
                    {{ end }}
                </ul>
            </nav>

        </div>
    </div>
</main>

<!-- Modal -->
<div class="modal fade" id="websiteModal" tabindex="-1" aria-labelledby="websiteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="websiteForm" action="/admin/websites/save" method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="websiteModalLabel">新增网站</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="websiteId" name="id" value="0">
                    <div class="form-group">
                        <label for="url">URL 必填项：系统会根据URL自动抓取信息</label>
                        <input type="text" class="form-control" id="url" name="url" required>
                        <br>
                        <button type="button" class="btn btn-danger btn-sm" id="fetchBtn">抓取</button>
                    </div>
                    <div class="form-group">
                        <label for="name">名称</label>
                        <input type="text" class="form-control" id="name" name="name" >
                    </div>
                    <div class="form-group">
                        <label for="groupId">分组</label>
                        <select class="form-control" id="groupId" name="group_id" required>
                            {{ range .groups }}
                            <option value="{{ .Id }}">{{ .Name }}</option>
                            {{ end }}
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="logo">Logo</label>
                        <input type="text" class="form-control" id="logo" name="logo" >
                        <img id="faviconPreview" src="" style="width:32px;margin-top:5px;display:none;" />
                    </div>


                    <div class="form-group">
                        <label for="description">描述</label>
                        <textarea class="form-control" id="description" name="description"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="/assets/admin/jquery-3.6.4.min.js"></script>
<script src="/assets/admin/popper.min.js"></script>
<script src="/assets/admin/bootstrap-4.6.2.min.js"></script>

<script>
    $(function () {

        // 抓取按钮点击事件
        $('#fetchBtn').on('click', function () {
            const url = $('#url').val().trim();

            if (!url) {
                alert('请输入有效的 URL');
                return;
            }

            // 使用正则验证 URL 格式
            const urlPattern = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w\.\-?=&]*)*\/?$/i;
            if (!urlPattern.test(url)) {
                alert('请输入合法的 URL，例如：https://example.com');
                return;
            }

            console.log("发送请求，URL:", url); // 调试输出

            $.ajax({
                url: '/admin/websites/fetch-meta',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ url: url }),
                success: function(res) {
                    if (res.code === 0) {
                        if (res.title) $('#name').val(res.title);
                        if (res.description) $('#description').val(res.description);
                        if (res.favicon) {
                            $('#logo').val(res.favicon);
                            $('#faviconPreview').attr('src', res.favicon).show();
                        }
                    } else {
                        alert('抓取失败: ' + (res.msg || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error("请求失败");
                    console.log("响应内容:", xhr.responseText);
                    alert('请求失败，请查看控制台日志');
                }
            });
        });


        // 其他函数也可以放在这里
        window.editWebsite = function(id, name, groupId, url, logo, description) {
            $('#websiteModalLabel').text('编辑网站');
            $('#websiteId').val(id);
            $('#name').val(name);
            $('#groupId').val(groupId);
            $('#url').val(url);
            $('#logo').val(logo);
            $('#description').val(description);
        };

        window.deleteWebsite = function(id) {
            if (confirm('确定要删除该网站吗？')) {
                $.post('/admin/websites/delete', {id: id}, function(res) {
                    if (res.code === 0) {
                        location.reload();
                    } else {
                        alert(res.msg);
                    }
                }, 'json');
            }
        };

        window.resetForm = function() {
            $('#websiteModalLabel').text('新增网站');
            $('#websiteId').val(0);
            $('#name').val('');
            $('#groupId').val('');
            $('#url').val('');
            $('#logo').val('');
            $('#description').val('');
        };
    });
</script>



</body>
</html>
{{end}}
